import 'package:flutter/cupertino.dart';
import 'package:flutter_todolist/db/db.dart';
import 'package:flutter_todolist/pages/home/home.dart';
import 'package:flutter_todolist/utils/auth.dart';
import 'package:flutter_todolist/utils/logger.dart';
import 'package:get/get.dart';

import '../../db/table/user_table.dart';
import '../../utils/common.dart';


class AuthLoginController extends GetxController {
  // var currentIndex = 0.obs;
  var passwordSecure = true.obs;
  // var passwordConfirmSecure = true.obs;

  TextEditingController accountCtrl = TextEditingController();
  TextEditingController passwordCtrl = TextEditingController();
  late UserTable userTable;

  @override
  void onInit() {
    userTable = ToDoDB().userTable;
    super.onInit();
  }

  void passwordSwitch() {
    passwordSecure.value = !passwordSecure.value;
  }

  Future<void> login() async {

    if (checkLogin()) {

      String account = accountCtrl.text;

      List<Map> dbAccounts = await userTable.queryList(
        where: "account = ?",
        whereArgs: [account]
          // where: "( uid = ? and receive_uid = ? ) or ( uid = ? and receive_uid = ? )",
          // whereArgs: [uid, receive_uid, receive_uid, uid],
          // orderBy: "ctime desc"
      );
      logW("adAccounts: $dbAccounts");
      if (dbAccounts.isEmpty) {
        showToast("当前账号不存在");
      } else {
        User user = User.fromJson(dbAccounts[0]);
        if (user.password == passwordCtrl.text) {
          Auth.login(user);
        } else {
          showToast('密码错误');
        }
      }
    }

  }

  bool checkLogin() {
    if (accountCtrl.text.isEmpty) {
      showToast('账号不能为空');
      return false;
    }

    if (passwordCtrl.text.isEmpty) {
      showToast('密码不能为空');
      return false;
    }

    return true;
  }

}